<template>
<div>
  <el-dialog
    :title="!dataForm.id ? $t('handle.add') : $t('handle.update')"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <div v-loading = loading>
    <el-tabs v-model="activeName" @tab-click="handleClick" >
      <el-tab-pane label="主要信息" name="first">
         <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="180px">
          <el-form-item label="地址元素类型" prop="type">
            <el-select v-model="dataForm.typeId" placeholder="请选择地址类型" @change="selectType">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上级区域" prop="addressName">
            <el-input v-model="parentName" placeholder="上级区域" disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="区域名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="区域名称"></el-input>
          </el-form-item>
          <el-form-item label="区域代码" prop="code">
            <el-input v-model="dataForm.code" placeholder="区域代码"></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="alias">
            <el-input v-model="dataForm.alias" placeholder="别名"></el-input>
          </el-form-item>
          <el-form-item label="设立日期" prop="establishmentDate">
          <el-date-picker
            v-model="dataForm.establishmentDate"
            type="date"
            placeholder="选择设立日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="撤销时间" prop="cancellationTime">
          <el-date-picker
            v-model="dataForm.cancellationTime"
            type="date"
            placeholder="选择撤销时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="dataForm.updateTime"
            type="date"
            placeholder="选择更新时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="启用日期" prop="openingDate">
          <el-date-picker
            v-model="dataForm.openingDate"
            type="date"
            placeholder="选择启用日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          </el-form-item>
          <el-form-item label="停用日期" prop="deactivationDate">
            <el-date-picker
              v-model="dataForm.deactivationDate"
              type="date"
              placeholder="选择停用日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="小区附属信息" name="second" v-if="showHousing">
        <el-form :model="housForm" :rules="HousRule" ref="housForm" label-width="180px" style="margin-top:15px">
          <el-form-item label="小区全称" prop="fullName">
            <el-input v-model="housForm.fullName" placeholder="小区全称"></el-input>
          </el-form-item>
          <el-form-item label="小区简称" prop="shortName">
            <el-input v-model="housForm.shortName" placeholder="小区简称"></el-input>
          </el-form-item>
          <el-form-item label="小区编码" prop="code">
            <el-input v-model="housForm.code" placeholder="小区编码"></el-input>
          </el-form-item>
          <el-form-item label="省/市/区/社区/居委会" prop="">
            <el-input v-model="pnames" :disabled="true"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="楼栋附属信息" name="third" v-if="showBuild">
        <el-form :model="buildForm" :rules="buildRule" ref="buildForm" label-width="120px" style="margin-top:15px">
          <el-form-item prop="housingEstateId" label="上级区域">
            <el-input v-model="pnames" placeholder="上级区域" :disabled="true"></el-input>
          </el-form-item>
          <!-- <el-form-item prop="griddingId" label="所属网格">
            <el-input v-model="buildForm.griddingId" placeholder="所属网格"></el-input>
          </el-form-item> -->
          <el-form-item prop="buildingFullName" label="楼栋全称">
            <el-input v-model="buildForm.buildingFullName" placeholder="楼栋全称"></el-input>
          </el-form-item>
          <el-form-item prop="buildingShortName" label="楼栋简称">
            <el-input v-model="buildForm.buildingShortName" placeholder="楼栋简称"></el-input>
          </el-form-item>
          <el-form-item label="选择网格" prop="graddingId">
            <el-input v-model="buildForm.griddingName"  placeholder="网格" :disabled="true" style="width:90%"></el-input><el-button style="width:10%" type="info" :disabled="isInput" plain @click="griddingDialogOpen()">选择</el-button>
          </el-form-item>
          <el-form-item prop="unitNumber" label="单元号">
            <el-input v-model="buildForm.unitNumber" placeholder="单元号"></el-input>
          </el-form-item>
          <el-form-item prop="floorNumber" label="楼层数">
            <el-input v-model="buildForm.floorNumber" placeholder="楼层数"></el-input>
          </el-form-item>
          <el-form-item prop="lowestLivingFloor" label="最低居住楼层">
            <el-input v-model="buildForm.lowestLivingFloor" placeholder="最低居住楼层"></el-input>
          </el-form-item>
          <el-form-item prop="highestLivingFloor" label="最高居住楼层">
            <el-input v-model="buildForm.highestLivingFloor" placeholder="最高居住楼层"></el-input>
          </el-form-item>
          <el-form-item prop="purpose" label="楼栋用途">
            <!-- <el-input v-model="buildForm.purpose" placeholder="楼栋用途"></el-input> -->
            <el-select style="width: 100%;" v-model="dataForm.purpose" filterable placeholder="请选择">
              <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="manageName" label="物管联系人姓名">
            <el-input v-model="buildForm.manageName" placeholder="物管联系人姓名"></el-input>
          </el-form-item>
          <el-form-item prop="managePhone" label="物管联系人电话">
            <el-input v-model="buildForm.managePhone" placeholder="物管联系人电话"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
      <div style="text-align:right;">
      <span slot="footer" class="dialog-footer">
        <el-button @click="callOf()">{{ $t('handle.cancel') }}</el-button>
        <el-button type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
      </span>
      </div>
    </div>
    </el-dialog>
      <address-Dialog v-if="addressVisible" ref="addressDialog" @receiveParameters="getAddressParameters"></address-Dialog>
    </div>
</template>

<script>
import AddressDialog from '../griddingDialog'
import { getDictList } from '@/utils'
import {validatenull,isMobile} from '@/utils/validate'
  export default {
    data () {
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
        } else {
        callback()
        }
      }
      return {
        loading:false,
        option: '',
        pnames: '',
        showHousing: false,
        showBuild: false,
        activeName: 'first',
        typeList:'',
        typeArray: [],
        visible: false,
        parentName: '',
        dataForm: {
          id: '',
          type: '',
          code: '',
          name: '',
          parentId: '',
          alias: '',
          isLeaf: '',
          pids: '',
          isAddress: '',
          establishmentDate: '',
          cancellationTime: '',
          updateTime: '',
          openingDate: '',
          deactivationDate: ''
        },
        housForm: {
          id: '',
          fullName: '',
          shortName: '',
          housCode: '',
          parentId: ''
        },
        buildForm: {
          id: '',
          housingEstateId: '',
          griddingId: '',
          buildingFullName: '',
          buildingShortName:'',
          unitNumber:'',
          floorNumber: '',
          lowestLivingFloor: '',
          highestLivingFloor: '',
          purpose: '',
          manageName: '',
          managePhone: '',
          griddingId: '',
          griddingName: ''

        },
        formValidate: '',
        housValidate: '',
        buildingFormValidate: '',
        addressVisible: '',
        isInput: false,
        buildRule: {

        },
        HousRule: {

        },
        dataRule: {
          typeId: [
            { required: true, message: '地址元素类型不能为空', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '区域代码不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '区域名称不能为空', trigger: 'blur' }
          ],
          parentId: [
            { required: true, message: '上级区域id不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
     'address-Dialog': AddressDialog
    },
    computed: {
      regionId() {
        return this.$store.state.address.regionId;
      },
      regionAllName() {
        return (this.$store.state.address.regionPnames ? this.$store.state.address.regionPnames + ',' : '') +this.$store.state.address.regionName;
      },
      regionTypeList() {
        return this.$store.state.address.regionTypeList;
      }
    },
    created(){
      this.getDictList()
      this.getPurpose()
    },
    methods: {
      // 点击选择网格触发的事件
      griddingDialogOpen(){
        this.addressVisible = true
        this.$nextTick(() => {
          this.$refs.addressDialog.init()
        })
      },
      getAddressParameters ( data ) {
        this.buildForm.griddingId = data.selectId
        this.buildForm.griddingName = data.selectText
      },
      // 获取码表
      getPurpose(){
        this.$http({
        url: 'dg-ic/ic/dict/type/purpose_type',
        method: 'get'
        }).then(({data})=>{
            if(data && data.code === 0){
              this.option = data.data
            }
        })
      },
      init () {
        this.$nextTick(() => {
          this.visible = true
          this.$http({
              url: `/dg-standard-info/dgstandardregion/info/${this.regionId}`,
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                var reg = new RegExp(',','g');
                this.pnames = data.data.pnames.replace(reg,'-')+'-'+data.data.name
              }
            })
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if(valid){
            this.formValidate = true
          }
        })
        if(this.showHousing){
          this.$refs['housForm'].validate((valid1)=>{
          if(valid1){
            this.housValidate = true
          }
          })
        }
        if(this.showBuild){
          this.$refs['buildForm'].validate((valid2)=>{
          if(valid2){
            this.buildingFormValidate = true
          }
          })
        }
        if(this.formValidate || this.buildingFormValidate || this.housValidate){
          this.loading = true
          this.$http({
              url:  '/dg-ic/ic/housing-estate/saveOrUpdate',
              method: 'post',
              data: this.$http.adornData({
                'typeId': this.dataForm.typeId,
                'code': this.dataForm.code,
                'name': this.dataForm.name,
                'parentId': this.regionId,
                'alias': this.dataForm.alias,
                'isLeaf': 1,
                'pids': `${this.pids},${this.regionId}`,
                'establishmentDate': this.dataForm.establishmentDate,
                'cancellationTime': this.dataForm.cancellationTime,
                'updateTime': this.dataForm.updateTime,
                'openingDate': this.dataForm.openingDate,
                'deactivationDate': this.dataForm.deactivationDate,
                // 小区
                'fullName': this.housForm.fullName,
                'shortName': this.housForm.shortName,
                'housCode': this.housForm.code,
                'parentId': this.regionId,
                // 楼栋
                'id': this.buildForm.id,
                'buildingParentId': this.regionId,
                'griddingId': this.buildForm.griddingId,
                'buildingFullName': this.buildForm.buildingFullName,
                'buildingShortName': this.buildForm.buildingShortName,
                'unitNumber': this.buildForm.unitNumber,
                'floorNumber': this.buildForm.floorNumber,
                'lowestLivingFloor': this.buildForm.lowestLivingFloor,
                'highestLivingFloor': this.buildForm.highestLivingFloor,
                'purpose': this.buildForm.purpose,
                'manageName': this.buildForm.manageName,
                'managePhone': this.buildForm.managePhone
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.loading = false
                    this.visible = false
                    this.global.refreshNode(this.global.treeNode);
                    this.dataForm.typeId = ''
                    this.$nextTick(()=>{
                      if(this.$refs[`dataForm`].resetFields() !== undefined){
                        this.$refs[`dataForm`].resetFields()
                      }
                      if(this.showHousing){
                        this.housForm = {}
                        this.showHousing = false
                        this.activeName = 'first'
                      }
                      if(this.showBuild){
                        this.buildForm = {}
                        this.showBuild = false
                        this.activeName = 'first'
                      }
                  })
                  }
                })
                //判断返回子集条数来更新node
                if(data.data.count === 1){//判断返回子集条数来更新node
                  this.global.refreshNode(this.global.treeNode.parent);
                }else{
                  this.global.refreshNode(this.global.treeNode);
                }
              } else {
                this.$message.error(data.msg)
              }
            })
        }
      },
      getDictList(){
        this.$http({
          url: `/dg-standard-info/dgregiontype/regiontypedictlist`,
          method: 'get',
          params: this.$http.adornParams()
          }).then(({data})=>{
            if(data && data.code === 0){
              // 如果是超级管理员可以添加小区，如果不是超级管理员不可以添加小区
              if(validatenull(sessionStorage.getItem("thiscommunityId"))){
                this.typeList = data.data.slice(11,data.data.length-1)
              }else{
                this.typeList = data.data.slice(12,data.data.length-1)
              }

            }
          })
      },
      handleClick(){

      },
      callOf(){
        this.visible = false
        this.showHousing = false
        this.showBuild = false
        this.dataForm.typeId = ''
        this.$nextTick(()=>{
          if(this.$refs[`dataForm`].resetFields() !== undefined){
            this.$refs[`dataForm`].resetFields()
          }
          if(!this.showHousing){
            this.housForm = {}
            this.activeName = 'first'
          }
          if(!this.showBuild){
            this.buildForm = {}
            this.activeName = 'first'
          }
        })
      },
      // Todo可以根据当前区域id去拿到区域信息，根据type.id值进行自动显示隐藏
      selectType(val){
        if(val === 42){
          this.showBuild = false
          this.showHousing= true
        }else if(val === 61){
          this.showHousing = false
          this.showBuild = true
        }else{
          this.showHousing = false
          this.showBuild = false
        }
      }
    }
  }
</script>
